//
//  ICEStoryManager.m
//  ICEViewPrototype
//
//  Created by Aurélien Ammeloot on 27/07/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ICEStoryManager.h"
#import "ICEStory.h"

@implementation ICEStoryManager
@synthesize stories = _stories;

#pragma mark -
#pragma mark Initialising

- (id)init
{
	if(self=[super init]) {
		_stories = [[NSMutableArray alloc] init];
		
		NSString *path = @"Stories";
		NSError *error;
		
		// Finding all paths in the directory
		path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:path];
		NSFileManager *manager = [NSFileManager defaultManager];
		NSArray *directories = [manager contentsOfDirectoryAtPath:[path stringByExpandingTildeInPath] error:&error];
		
		// Counter for story IDs
		int i=0;
		// Importing stories from the directory
		for (NSString *directory in directories) {
			
			// Creating a story, giving it the name of the directory, and an ID
			ICEStory *story = [[ICEStory alloc] init];
			story.identifier = i;
			story.title = directory;
			story.author = @"Ann Onymous";
			
			NSString *dirPath = [path stringByAppendingPathComponent:directory];
			story.baseFolder = dirPath;
			
			// Counting how many HTML files are in the folder and incrementing
			int pageNumber = 0;
			NSArray *files = [manager contentsOfDirectoryAtPath:dirPath error:&error];
			for (NSString *file in files) {
				if([file hasSuffix:@".html"])
					pageNumber++;
			}
			story.length = pageNumber;
			
			// Adding story to the array and dereferencing
			[_stories addObject:story];
			[story release];
			i++;
		}
	}
	return self;
}

+ (id)sharedManager
{
	static ICEStoryManager *singleton = nil;
	if(singleton == nil) {
		singleton = [[ICEStoryManager alloc] init];
	}
	return singleton;
}

@end
